//
//  HEAfterSaleViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/13.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEAfterSaleViewController.h"
#import "HEAfterGoodsCell.h"
#import "HEAfterTypeSelectCell.h"
#import "HEAfterRefundPriceCell.h"
#import "HEAfterPhotoCell.h"
#import "HEAfterTextViewCell.h"

@interface HEAfterSaleViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *formArrs;
@property (nonatomic, strong) NSMutableArray *imgsArr;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@end

@implementation HEAfterSaleViewController

- (NSMutableArray *)imgsArr {
    if (!_imgsArr) {
        _imgsArr = @[].mutableCopy;
    }
    return _imgsArr;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"申请售后";
    
    // 总段
    _sections = [NSMutableArray array];
    _formArrs = [NSMutableArray array];
 
    [self.view addSubview:self.tableView];
    [self setupFooterView];
    
    [self initCell];
    
    [self catuPrice];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)setupFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 100)];
    footerView.backgroundColor = KWhiteColor;
    
    // 保存按钮
    QMUIFillButton *saveBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    saveBtn.titleLabel.font = DYBlodFont(16);
    [saveBtn setBackgroundColor:CNavBgColor];
    [saveBtn setTitle:@"提 交" forState:UIControlStateNormal];
    [footerView addSubview:saveBtn];
    [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView).mas_offset(30);
        make.left.equalTo(footerView).mas_offset(50);
        make.right.equalTo(footerView).mas_offset(-50);
        make.height.mas_offset(40);
    }];
    
    self.tableView.tableFooterView = footerView;
}

- (void)saveClick {
    
    BOOL hasGoods = NO;
    for (HEOrderItemModel *model in _orderItems) {
        if (model.isChoose) {
            hasGoods = YES;
        }
    }
    
    if (!hasGoods) {
        if (self.formModel.as_type == HEOrderAfterSalesTypeRefund) {
            [Dialog toastBottom:@"请选择需要退款的商品"];
        }else if (self.formModel.as_type == HEOrderAfterSalesTypeReturnMoneyAndGoods){
            [Dialog toastBottom:@"请选择需要申请退款退货的商品"];
        }else {
            [Dialog toastBottom:@"请选择需要申请售后的商品"];
        }
        return;
    }
    
    if ([DYTools isBlankString:self.formModel.as_content]) {
        [Dialog toastBottom:@"请详细描述您遇到的问题~"];
        return;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        [self uploadImage: self.formModel];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createSubmitRequest];
        });
    });
    

}

- (void)createSubmitRequest {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:[NSNumber numberWithInteger:_model.id] forKey:@"orderId"];
    [params setValue:self.formModel.as_content forKey:@"desc"];
    [params setValue:self.formModel.as_returnAmount forKey:@"returnAmount"];
    [params setValue:[NSNumber numberWithInteger: self.formModel.as_type] forKey:@"type"];

    NSMutableArray *ids = @[].mutableCopy;
    for (HEOrderItemModel *model in _orderItems) {
        if (model.isChoose) {
            [ids addObject: [NSNumber numberWithInteger:model.id]];
        }
    }
    [params setValue:[ids componentsJoinedByString:@","] forKey:@"items"];
    [params setValue:[self.formModel.cm_imgUrls componentsJoinedByString:@","] forKey:@"images"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KsaveOmsOrderReturnApply parameters:params success:^(id  _Nonnull responseObject) {

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"申请售后成功~"];
            if (self.backBlock) {
                self.backBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

#pragma mark -

- (void)initCell {
    
    _sections = @[].mutableCopy;

    NSMutableArray *classArr = [NSMutableArray array];
    
    self.formModel.od_details = _model;
    self.formModel.od_itemList = [NSMutableArray arrayWithArray:_orderItems];
    self.formModel.as_returnAmount = @"0";
    
    // 商品
    GDFiterCellModel *goodModel = [GDFiterCellModel new];
    goodModel.cellKlass = HEAfterGoodsCell.class;
    goodModel.cellType = GDFiterCellTypeOrderGoods;
    
    // 选择退款类型
    GDFiterCellModel *refundTypeModel = [GDFiterCellModel new];
    refundTypeModel.cellKlass = HEAfterTypeSelectCell.class;
    
    // 退款金额
    GDFiterCellModel *priceModel = [GDFiterCellModel new];
    priceModel.cellKlass = HEAfterRefundPriceCell.class;
    
    // 上传图片
    GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEAfterPhotoCell.class;
    photoModel.leftTitle = @"上传照片";
    photoModel.cellType = GDFiterCellTypeSelect_ADDPHOTO;
    photoModel.cellHeight = 180;
    
    // 文本描述
    GDFiterCellModel *textModel = [GDFiterCellModel new];
    textModel.cellKlass = HEAfterTextViewCell.class;
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[goodModel, refundTypeModel, priceModel, photoModel, textModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    for (GDFiterCellModel *model in classArr) {
        NSMutableArray *rows = @[].mutableCopy;

        if (model.cellType == GDFiterCellTypeOrderGoods) {
         
            for (HEOrderItemModel *item in _orderItems ) {
                [rows addObject: model];
            }
        }else {
            [rows addObject:model];
        }
        [_sections addObject:rows];
    }
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *rows = _sections[section];
    return rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *rows = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = rows[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *rows = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = rows[indexPath.row];
//    GDFormModel *formModel = _formArrs[indexPath.section];
//
    if (fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO) {
        return fiterModel.cellHeight;
    }
    
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *rows = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = rows[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeOrderGoods) {
        [self changeGoodsSelectSatate:indexPath];
        
        [self catuPrice];
    }
}

// 改变某个段的所有选中状态
- (void)changeGoodsSelectSatate:(NSIndexPath *)indexPath {
    HEOrderItemModel *model = _orderItems[indexPath.row];
    model.isChoose = !model.isChoose;
    [self.tableView reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];;
}

- (void)catuPrice {
    
    NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"0"];
    for (HEOrderItemModel *model in _orderItems) {
        if (!model.isChoose) {
            continue;;
        }
        NSDecimalNumber *p1 = [NSDecimalNumber decimalNumberWithString:model.productPrice];
        NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%ld", model.productQuantity]];
        NSDecimalNumber *totalP1 = [p1 decimalNumberByMultiplyingBy: num];
        price = [price decimalNumberByAdding: totalP1];
    }
    
    self.formModel.as_returnAmount = price.stringValue;
    [self.tableView reloadData];
}

@end
